package com.aqie.meet.ui.home;

import android.os.Build;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aqie.libcommon.app.PresenterFragment;
import com.aqie.libcommon.utils.DateTimeUtil;
import com.aqie.libcommon.widget.EmptyView;
import com.aqie.libcommon.widget.PortraitView;
import com.aqie.libcommon.widget.recycle.RecyclerAdapter;
import com.aqie.libfactory.Factory;
import com.aqie.libfactory.data.helper.DbHelper;
import com.aqie.libfactory.data.helper.SessionHelper;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.api.chat.UnReadMessage;
import com.aqie.libfactory.model.card.MessageCard;
import com.aqie.libfactory.model.db.Session;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.libfactory.presenter.message.SessionContract;
import com.aqie.libfactory.presenter.message.SessionPresenter;
import com.aqie.libnavanotation.FragmentDestination;
import com.aqie.meet.R;
import com.aqie.meet.ui.chat.MessageActivity;
import com.aqie.meet.ui.search.SearchActivity;
import com.bumptech.glide.Glide;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@FragmentDestination(pageUrl = "main/tabs/home", asStarter = false,needLogin = true)
public class HomeFragment extends PresenterFragment<SessionContract.Presenter>
        implements SessionContract.View  {


    @BindView(R.id.empty_view)
    EmptyView mEmptyView;

    @BindView(R.id.recycler_view)
    RecyclerView mRecycleView;

    @BindView(R.id.im_search)
    ImageView mSearch;

    private RecyclerAdapter<Session> mAdapter;

    public HomeFragment() {
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_home;
    }


    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        initView();
    }

    @Override
    protected void onFirstInit() {
        super.onFirstInit();
        // 进行一次数据加载
        mPresenter.start();
    }

    private void initView() {
        mRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleView.setAdapter(mAdapter = new RecyclerAdapter<Session>() {
            @Override
            protected int getItemViewType(int position, Session session) {
                // 返回cell的布局id
                return R.layout.cell_chat_list;
            }

            @Override
            protected ViewHolder<Session> onCreateViewHolder(View root, int viewType) {
                return new HomeFragment.ViewHolder(root);
            }
        });

        // 点击事件监听
        mAdapter.setListener(new RecyclerAdapter.AdapterListenerImpl<Session>() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, Session session) {
                // 跳转到聊天界面
                /*MessageActivity.show(getContext(), session);*/
            }

        });

        // 初始化占位布局
        mEmptyView.bind(mRecycleView);
        setPlaceHolderView(mEmptyView);

    }

    @Override
    public void onResume() {
        super.onResume();
        // BaseApplication.showToast("HomeFragment onResume");
        unReadMsgList();
    }

    @Override
    protected SessionContract.Presenter initPresenter() {
        return new SessionPresenter(this);
    }

    @Override
    public RecyclerAdapter<Session> getRecyclerAdapter() {
        return mAdapter;
    }

    @Override
    public void onAdapterDataChanged() {
        mPlaceHolderView.triggerOkOrEmpty(mAdapter.getItemCount() > 0);
    }


    // 界面数据渲染
    class ViewHolder extends RecyclerAdapter.ViewHolder<Session> {

        @BindView(R.id.chat)
        FrameLayout mChat;
        @BindView(R.id.im_portrait)
        PortraitView mPortraitView;

        @BindView(R.id.txt_name)
        TextView mName;

        @BindView(R.id.txt_content)
        TextView mContent;

        @BindView(R.id.txt_time)
        TextView mTime;

        @BindView(R.id.chat_badge)
        TextView mBadge;

        ViewHolder(View itemView) {
            super(itemView);
        }

        /**
         * 单条聊天记录数据渲染
         * @param session
         */
        @Override
        protected void onBind(Session session) {
            if (session != null) {
                if(session.getTitle() != null){
                    // 头像
                    mPortraitView.setup(Glide.with(HomeFragment.this), session.getPicture());
                    // 用户名
                    mName.setText(session.getTitle());
                }
                String str = TextUtils.isEmpty(session.getContent()) ? "" : session.getContent();
                Spannable spannable = new SpannableString(str);

                // 把聊天内容设置到布局上
                mContent.setText(spannable);
                // 聊天时间
                mTime.setText(DateTimeUtil.getSampleDate(session.getModifyAt()));
                if(session.getUnReadCount() > 0){
                    mBadge.setVisibility(View.VISIBLE);
                } else {
                    mBadge.setVisibility(View.GONE);
                }
                mChat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBadge.setVisibility(View.GONE);
                        session.setUnReadCount(0);
                        DbHelper.save(Session.class, session);
                        // 跳转到聊天界面
                        MessageActivity.show(getContext(), session);
                    }
                });

            }
        }
    }

    // 点击搜索人才按钮
    @OnClick(R.id.im_search)
    void onSearchMenuClick() {
        SearchActivity.show(getActivity(), SearchActivity.TYPE_CHAT);
    }

    List<UnReadMessage> unReadMessages;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private void unReadMsgList() {
        RemoteService service = Network.remote();
        Call<RspModel<List<UnReadMessage>>> call = service.unReadMsgList();
        call.enqueue(new Callback<RspModel<List<UnReadMessage>>>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(Call<RspModel<List<UnReadMessage>>> call, Response<RspModel<List<UnReadMessage>>> response) {
                RspModel<List<UnReadMessage>> body = response.body();

                /*if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }*/
                if(body !=null && body.success()){
                    // BaseApplication.showToast("拉取未读消息成功");
                    unReadMessages = body.getData();
                    // String rspString = SimpleJsonTool.toJson(unReadMessages); Log.e("UNREAD", rspString);
                    // 进行消息派发
                    List<MessageCard> cardsList = new ArrayList<>();
                    unReadMessages.forEach((item) -> {
                        MessageCard card = new MessageCard();
                        card.setMsg(item.getMsg());
                        card.setMsgId(item.getId());
                        card.setReceiverId(item.getReceiverId());
                        card.setSenderId(item.getSenderId());
                        card.setSign(1);
                        try {
                            card.setCreateAt(sdf.parse(item.getCreateTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        cardsList.add(card);
                    });

                    MessageCard[] cards = cardsList.toArray(new MessageCard[0]);
                    if(cards.length > 0){
                        Factory.getMessageCenter().dispatch(cards);
                        // 保存消息到数据库
                        // DbHelper.save(Message.class, cards);
                        // BaseApplication.showToast("未读消息进行派发");
                    } else {
                        // senderId='1361630891778039809', receiverId='1359794072186822658'
                        // BaseApplication.showToast("无未读消息");
                        SessionHelper.updateAllUnReadNumber();
                        /*String id = "1361630891778039809";
                        Long unSignMessageCount = MessageHelper.findUnSignMessageCount(id);
                        Log.e("UNREAD", id + " 未读消息数 " + unSignMessageCount);
                        List<Session> sessions = SessionHelper.searchAllSession();
                        Log.e("UNREAD", sessions.toString());*/
                    }

                }
            }

            @Override
            public void onFailure(Call<RspModel<List<UnReadMessage>>> call, Throwable t) {

            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            // BaseApplication.showToast("onHiddenChanged 界面更新");
        }
    }
}